﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace Petra.Gis.DataServices.WKB.Support
{
  //intel = littleEndian
  //motorola = bigEndian
  internal static class EndianConverter
  {

    internal static WKB.ByteOrder GetCurrentPlatformEndian() {
      if (BitConverter.IsLittleEndian)
        return WKB.ByteOrder.LittleIndian;
      else
        return WKB.ByteOrder.BigIndian;

    }




    internal static bool NeedEndianConversion(WKB.ByteOrder dataEndian) 
    {
      if ((dataEndian == WKB.ByteOrder.BigIndian && BitConverter.IsLittleEndian) || (dataEndian == WKB.ByteOrder.LittleIndian && !BitConverter.IsLittleEndian))
        return true;
      else
        return false;
    }




    internal static int ToInt32(Int32 val, WKB.ByteOrder dataEndian)
    {

      //check endian of current platform
      if (NeedEndianConversion(dataEndian))
      {
        byte[] b = BitConverter.GetBytes(val);
        Array.Reverse(b);
        return BitConverter.ToInt32(b, 0);
      }
      else
      {
        return val;
      }
    }




    internal static double ToDouble(Double val, WKB.ByteOrder dataEndian)
    {

      //check endian of current platform
      byte[] b;
      if (NeedEndianConversion(dataEndian))
      {
        b = BitConverter.GetBytes(val);
        Array.Reverse(b);
        return BitConverter.ToDouble(b, 0);
      }
      else
      {
        return val;
      }
    }




    /*
    internal static byte[] ToArray(Double val, WKB.ByteOrder dataEndian)
    {

      //check endian of current platform
      byte[] b;
      if ((dataEndian == WKB.ByteOrder.BigIndian && BitConverter.IsLittleEndian) || (dataEndian == WKB.ByteOrder.LittleIndian && !BitConverter.IsLittleEndian))
      {
        b = BitConverter.GetBytes(val);
        Array.Reverse(b);
        return b;
      }
      else
      {
        return BitConverter.GetBytes(val);
      }
    }




    internal static byte[] ToArray(Int32 val, WKB.ByteOrder dataEndian)
    {

      //check endian of current platform
      byte[] b;
      if ((dataEndian == WKB.ByteOrder.BigIndian && BitConverter.IsLittleEndian) || (dataEndian == WKB.ByteOrder.LittleIndian && !BitConverter.IsLittleEndian))
      {
        b = BitConverter.GetBytes(val);
        Array.Reverse(b);
        return b;
      }
      else
      {
        return BitConverter.GetBytes(val);
      }
    }
    */


  }
}
